layui.use(['table', 'treetable', 'iconPickerFa'], function () {
    const $ = layui.jquery;
    const table = layui.table;
    const treetable = layui.treetable;
    var iconPicker = layui.iconPickerFa;

    renderTable(treetable);

    $('#btn-expand').click(function () {
        treetable.expandAll('#munu-table');
    });

    $('#btn-fold').click(function () {
        treetable.foldAll('#munu-table');
    });

    $('#btn-refresh').click(function () {
        renderTable(treetable);
    });

    $('#btn-shouye').click(function () {
        updateShouye();
    });

    iconPicker.render({
        // 选择器，推荐使用input
        elem: '#menuIcon',
        url: "/layui-v2.8.0/font-awesome-4.7.0/less/variables.less",
        // 是否开启搜索：true/false，默认true
        search: true,
        // 是否开启分页：true/false，默认true
        page: true,
        // 每页显示数量，默认12
        limit: 20,
        // 每个图标格子的宽度：'43px'或'20%'
        cellWidth: '16%',
        // 点击回调
        click: function (data) {
           $("#menuIcon").val("fa "+data.icon);
        },
    });

    //监听工具条
    table.on('tool(munu-table)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'del') {
            if (data.authorityId === 1) {
                lay_tishi("根节点不能修改！");
                return false;
            }
            layer.open({
                title: "删除",
                btn: ['确定', '取消'],
                content: ' 权限名称：' + data.authorityName,
                yes: function (index, layero) {
                    const dataFormValue = 'id=' + parseInt(data.authorityId) + '&menuCode=' + data.menuCode;
                    var jsonAuthAjax = JSONAuthAjax(dl_coder_url.delete_menu[0], dl_coder_url.delete_menu[1], dataFormValue);
                    if (jsonAuthAjax.code === '200') {
                        renderTable(treetable);
                        layer.close(index);
                    }
                }
            });

        } else if (layEvent === 'add') {
            form_init_add(data,iconPicker);
            layer.open({
                type: 1,
                title: "新增",
                area: ['60%', '70%'],
                btn: ['确定', '取消'],
                content: $('#menu-add-update'),
                yes: function (index, layero) {
                    layui.use(['form'], function () {
                        const form = layui.form;
                        formValue(form, index, treetable, '1');
                    });
                }
            });

        } else if (layEvent === 'edit') {
            if (form_init_update(data,iconPicker)) {
                layer.open({
                    type: 1,
                    title: "修改",
                    area: ['50%', '90%'],
                    btn: ['确定', '取消'],
                    content: $('#menu-add-update'),
                    yes: function (index, layero) {
                        layui.use(['form'], function () {
                            const form = layui.form;
                            formValue(form, index, treetable, '2');
                        });
                    }
                });
            }

        }
    });
});

function form_init_add(rowData,iconPicker) {
    $("#parentName_div").attr("style", "display:block;");
    $("#parentMenuCode_div").attr("style", "display:block;");
    iconPicker.checkIcon('menuIcon', '');
    layui.use('form', function () {
        var form = layui.form;
        $("#menu-add-update-form")[0].reset();
        //给表单赋值
        form.val("menu_form", {
            "parentId": rowData.authorityId,
            "parentName": rowData.authorityName,
            "parentMenuCode": rowData.menuCode
        });
    });
}

function form_init_update(rowData,iconPicker) {

    if (rowData.authorityId === 1) {
        lay_tishi("根节点不能修改！");
        return false;
    }
    $("#parentName_div").attr("style", "display:none;");
    $("#parentMenuCode_div").attr("style", "display:none;");


    layui.use('form', function () {
        var form = layui.form;
        $("#menu-add-update-form")[0].reset();
        var replace = rowData.menuIcon.replace('fa ','');
        // iconPicker.checkIcon('menuIcon', rowData.menuIcon);
        iconPicker.checkIcon('menuIcon', replace);
        // $("#menuIcon").val( replace);
        $("#menuIcon").val( rowData.menuIcon);

        //给表单赋值
        form.val("menu_form", {
            "authorityId": rowData.authorityId,
            "authorityName": rowData.authorityName,
            "authority": rowData.authority,
            "menuUrl": rowData.menuUrl,
            "isMenu": rowData.isMenu,
            "orderNumber": rowData.orderNumber,
            "parentId": rowData.parentId,
            "menuCode": rowData.menuCode,
            "auth": rowData.auth,
        });
    });

    return true;
}

function formValue(form, index, treetable, type) {
    form.render();
    if (!form.validate('#authorityName')) {
        lay_msg("权限名不能为空");
        return false;
    }

    if (!form.validate('#menuCode')) {
        lay_msg("权限编码不能为空");
        return false;
    }

    const dataFormValue = $("#menu-add-update-form").serializeJson();
    var resultData;
    //新增
    if (type === "1") {
        resultData = JSONAuthAjax(dl_coder_url.add_menu[0], dl_coder_url.add_menu[1], dataFormValue);
    } else {
        //修改
        resultData = JSONAuthAjax(dl_coder_url.update_menu[0], dl_coder_url.update_menu[1], dataFormValue);
    }
    if (resultData.code === '200') {
        renderTable(treetable);
        layer.close(index);
    }
}

function updateShouye() {
    var shouyeInfo = JSONAuthAjax(dl_coder_url.get_shouye_info[0], dl_coder_url.get_shouye_info[1]);
    if (shouyeInfo.code !== http_ok) {
        return;
    }

    $("#shouyeTitle").val(shouyeInfo.data.title);
    $("#shouyeHref").val(shouyeInfo.data.href);

    layer.open({
        type: 1,
        title: "修改首页",
        area: ['50%', '50%'],
        btn: ['确定', '取消'],
        content: $('#menu-shouye-update-add-from'),
        yes: function (index, layero) {
            layui.use(['form'], function () {
                const form = layui.form;
                shouyeFormValue(form, index);
            });
        }
    });
}

function shouyeFormValue(form, index) {
    form.render();
    if (!form.validate('#user-update-add-from')) {
        return false;
    }
    const dataFormValue = {'shouyeTitle': $('#shouyeTitle').val(), 'shouyeHref': $('#shouyeHref').val()};
    //修改
    var resultData = JSONAuthAjax(dl_coder_url.save_shouye_info[0], dl_coder_url.save_shouye_info[1], dataFormValue);

    if (resultData.code === '200') {
        layer.close(index);
    }
}


function renderTable(treetable) {
    // 渲染表格
    treetable.render({
        treeColIndex: 1,
        treeSpid: 0,
        treeIdName: 'authorityId',
        treePidName: 'parentId',
        elem: '#munu-table',
        url: dl_coder_url.resourceMenu[0],
        page: false,
        requestType: dl_coder_url.resourceMenu[1], //这里可以写post请求,默认get
        headers: headerMap,
        where: null,
        cols: [[
            {type: 'numbers'},
            {field: 'authorityName', align: 'center', minWidth: 200, title: '权限名称'},
            {field: 'authority', align: 'center', width: 100, title: '权限按钮'},
            {field: 'menuUrl', align: 'center', width: 200, title: '菜单url'},
            {field: 'menuCode', align: 'center', title: '权限编码'},
            {field: 'menuIcon', align: 'center', width: 30,title: '图标', templet: function (d) {
                        return '<i class="'+d.menuIcon+'"></i>';

                }},
            {field: 'auth', align: 'center', title: '接口权限'},
            {field: 'orderNumber', width: 80, align: 'center', title: '排序号'},
            {
                field: 'isMenu', width: 80, align: 'center', templet: function (d) {
                    if (d.isMenu === '2') {
                        return '<span class="layui-badge layui-bg-gray">按钮</span>';
                    }
                    if (d.parentId === 0 && d.isMenu === '1') {
                        return '<span class="layui-badge layui-bg-blue">目录</span>';
                    } else {
                        return '<span class="layui-badge-rim">菜单</span>';
                    }
                }, title: '类型'
            },
            {templet: '#auth-state', width: 230, align: 'center', title: '操作'}
        ]],
        done: function () {
            setAuthority();
        }
    });
}